{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensorflow.keras import layers\n",
    "from tensorflow.keras import models"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model: \"vgg16\"\n",
      "_________________________________________________________________\n",
      " Layer (type)                Output Shape              Param #   \n",
      "=================================================================\n",
      " input_1 (InputLayer)        [(None, 150, 150, 3)]     0         \n",
      "                                                                 \n",
      " block1_conv1 (Conv2D)       (None, 150, 150, 64)      1792      \n",
      "                                                                 \n",
      " block1_conv2 (Conv2D)       (None, 150, 150, 64)      36928     \n",
      "                                                                 \n",
      " block1_pool (MaxPooling2D)  (None, 75, 75, 64)        0         \n",
      "                                                                 \n",
      " block2_conv1 (Conv2D)       (None, 75, 75, 128)       73856     \n",
      "                                                                 \n",
      " block2_conv2 (Conv2D)       (None, 75, 75, 128)       147584    \n",
      "                                                                 \n",
      " block2_pool (MaxPooling2D)  (None, 37, 37, 128)       0         \n",
      "                                                                 \n",
      " block3_conv1 (Conv2D)       (None, 37, 37, 256)       295168    \n",
      "                                                                 \n",
      " block3_conv2 (Conv2D)       (None, 37, 37, 256)       590080    \n",
      "                                                                 \n",
      " block3_conv3 (Conv2D)       (None, 37, 37, 256)       590080    \n",
      "                                                                 \n",
      " block3_pool (MaxPooling2D)  (None, 18, 18, 256)       0         \n",
      "                                                                 \n",
      " block4_conv1 (Conv2D)       (None, 18, 18, 512)       1180160   \n",
      "                                                                 \n",
      " block4_conv2 (Conv2D)       (None, 18, 18, 512)       2359808   \n",
      "                                                                 \n",
      " block4_conv3 (Conv2D)       (None, 18, 18, 512)       2359808   \n",
      "                                                                 \n",
      " block4_pool (MaxPooling2D)  (None, 9, 9, 512)         0         \n",
      "                                                                 \n",
      " block5_conv1 (Conv2D)       (None, 9, 9, 512)         2359808   \n",
      "                                                                 \n",
      " block5_conv2 (Conv2D)       (None, 9, 9, 512)         2359808   \n",
      "                                                                 \n",
      " block5_conv3 (Conv2D)       (None, 9, 9, 512)         2359808   \n",
      "                                                                 \n",
      " block5_pool (MaxPooling2D)  (None, 4, 4, 512)         0         \n",
      "                                                                 \n",
      "=================================================================\n",
      "Total params: 14,714,688\n",
      "Trainable params: 14,714,688\n",
      "Non-trainable params: 0\n",
      "_________________________________________________________________\n"
     ]
    }
   ],
   "source": [
    "from tensorflow.keras.applications import VGG16\n",
    "\n",
    "conv_base = VGG16(weights='imagenet',\n",
    "                  include_top=False, \n",
    "                  input_shape=(150, 150, 3))\n",
    "\n",
    "conv_base.summary()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensorflow.keras.preprocessing.image import ImageDataGenerator\n",
    "\n",
    "datagen = ImageDataGenerator(rescale=1./255)\n",
    "batch_size = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "def extract_features(directory, sample_count):\n",
    "    features = np.zeros(shape=(sample_count, 4, 4, 512))\n",
    "    labels = np.zeros(shape=(sample_count))\n",
    "    \n",
    "    generator = datagen.flow_from_directory(\n",
    "        directory,\n",
    "        target_size=(150, 150),\n",
    "        batch_size=batch_size,\n",
    "        class_mode='binary')\n",
    "    \n",
    "    i = 0\n",
    "    \n",
    "    for inputs_batch, labels_batch in generator:\n",
    "        features_batch = conv_base.predict(inputs_batch)\n",
    "        \n",
    "        features[i * batch_size : (i + 1) * batch_size] = features_batch\n",
    "        labels[i * batch_size : (i + 1) * batch_size] = labels_batch\n",
    "        \n",
    "        i += 1\n",
    "        if i * batch_size >= sample_count:\n",
    "            # Note that since generators yield data indefinitely in a loop, \n",
    "            # we must `break` after every image has been seen once.\n",
    "            break\n",
    "    return features, labels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found 1000 images belonging to 2 classes.\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "base_dir = './new_data_base'\n",
    "test_dir = os.path.join(base_dir, 'test')\n",
    "test_feature, test_labels = extract_features(test_dir, 1000)\n",
    "test_feature = np.reshape(test_feature, (1000, 4 * 4 * 512))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "model = models.load_model(\"./cats_and_dogs_vgg16_my.h5\")\n",
    "predict_x = model.predict(test_feature)\n",
    "\n",
    "# plt.figure()\n",
    "\n",
    "# len = range(0, 51)\n",
    "# plt.plot(len, predict_x[:51], label='test') \n",
    "# plt.scatter(len, test_labels[:51], color='r',label='label') \n",
    "# plt.title('test result')\n",
    "# plt.legend()\n",
    "# plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 102,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "------------------\n",
      "<class 'numpy.ndarray'> [1.    1.    1.    0.784 0.997 0.    0.232 0.962 0.005 0.999]\n",
      "<class 'numpy.ndarray'> [1. 1. 1. 1. 1. 0. 0. 1. 0. 1.]\n"
     ]
    },
    {
     "ename": "TypeError",
     "evalue": "'range' object is not callable",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32mC:\\Users\\DENGXI~1\\AppData\\Local\\Temp/ipykernel_111164/2386861506.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m     12\u001b[0m \u001b[0mf2\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mnp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mwhere\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mxx\u001b[0m \u001b[1;33m<\u001b[0m \u001b[1;33m-\u001b[0m\u001b[1;36m0.5\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     13\u001b[0m \u001b[0mll\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mlist\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mxx\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mf1\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 14\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mlen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mll\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     15\u001b[0m \u001b[0mll2\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mlist\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mxx\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mf2\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     16\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mll2\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mTypeError\u001b[0m: 'range' object is not callable"
     ]
    }
   ],
   "source": [
    "np.set_printoptions(precision=3, suppress=True)\n",
    "#print(predict_x)\n",
    "print('------------------')\n",
    "#print(test_labels)\n",
    "predict_x = predict_x.reshape(1000,)\n",
    "print(type(predict_x), predict_x[0:10])\n",
    "print(type(test_labels), test_labels[0:10])\n",
    "\n",
    "xx = predict_x - test_labels\n",
    "#print(xx)\n",
    "f1 = np.where(xx > 0.5)\n",
    "f2 = np.where(xx < -0.5)\n",
    "ll = list(xx[f1])\n",
    "print(type(ll), ll)\n",
    "ll2 = list(xx[f2])\n",
    "print(ll2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(array([ 3,  4,  6,  7,  8, 10, 11, 12, 13, 15], dtype=int64),)\n"
     ]
    }
   ],
   "source": [
    "arr = np.array([1, 1, 1, 134, 45, 3, 46, 45, 65, 3, 23424, 234, 12, 12, 3, 546, 1, 2])\n",
    "print(np.where(arr > 3))\n",
    "#print(arr[np.where(arr == 3)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found 2 images belonging to 1 classes.\n"
     ]
    }
   ],
   "source": [
    "base_dir2 = '.\\\\new_data_base'\n",
    "test_dir2 = os.path.join(base_dir, 'mytest')\n",
    "test_feature2, test_labels2 = extract_features(test_dir2, 2)\n",
    "test_feature2 = np.reshape(test_feature2, (2, 4 * 4 * 512))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0.999982  ]\n",
      " [0.00145763]]\n"
     ]
    }
   ],
   "source": [
    "predict_x2 = model.predict(test_feature2)\n",
    "print(predict_x2)"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "a8f61be024eba58adef938c9aa1e29e02cb3dece83a5348b1a2dafd16a070453"
  },
  "kernelspec": {
   "display_name": "Python 3.9.7 64-bit ('base': conda)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
